package com.jz.community.moduleshopping.cardGoods.ui;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.commview.view.recyclerView.SpaceItemDecoration;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.cardGoods.adapter.CardBrandAdapter;
import com.jz.community.moduleshopping.cardGoods.adapter.CardBrandCategoryAdapter;
import com.jz.community.moduleshopping.cardGoods.adapter.CardHomeAdapter;
import com.jz.community.moduleshopping.cardGoods.info.CardBrandInfo;
import com.jz.community.moduleshopping.cardGoods.info.CardHomeInfo;
import com.jz.community.moduleshopping.cardGoods.task.GetCardBrandTask;
import com.jz.community.moduleshopping.cardGoods.task.GetCardClassifyTask;
import com.yarolegovich.discretescrollview.DiscreteScrollView;
import com.yarolegovich.discretescrollview.transform.ScaleTransformer;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/8/16 09:11
 */
@Route(path = RouterIntentConstant.CARD_HOME)
public class CardHomeActivity extends BaseMvpActivity implements DiscreteScrollView.OnItemChangedListener<RecyclerView.ViewHolder>, DiscreteScrollView.ScrollStateChangeListener<RecyclerView.ViewHolder> {

    @BindView(R2.id.title_back_left)
    ImageView titleBackLeft;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.title_right_iv)
    ImageView titleRightIv;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.card_recyclerView)
    RecyclerView cardRecyclerView;
    @BindView(R2.id.no_data_empty)
    LinearLayout no_data_empty;
    @BindView(R2.id.emptyTxt)
    TextView emptyTxt;

    RecyclerView card_brand_recyclerView;
    TextView cardBrandNameTv;
    DiscreteScrollView cardBrandRv;
    LinearLayout cardBrandGoodsLayout;
    private CardBrandAdapter cardBrandAdapter;
    private CardHomeAdapter cardHomeAdapter;
    private CardBrandCategoryAdapter cardBrandCategoryAdapter;
    private View headView;
    private View footView;
    private CardBrandInfo cardBrandInfo;
    private int positionInDataSet;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_card_home_layout;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(titleToolbar);
        titleName.setText("卡多多");
        headView();
        footView();
    }

    private void headView() {
        headView = LayoutInflater.from(this).inflate(R.layout.module_shopping_card_head_item_layout, (ViewGroup) cardRecyclerView.getParent(), false);
        cardBrandRv = headView.findViewById(R.id.card_brand_rv);
        cardBrandNameTv = headView.findViewById(R.id.card_brand_name_tv);
        card_brand_recyclerView = headView.findViewById(R.id.card_brand_recyclerView);
        cardBrandGoodsLayout = headView.findViewById(R.id.card_brand_goods_layout);
    }

    private void footView() {
        footView = LayoutInflater.from(this).inflate(R.layout.module_shopping_card_end_more_layout, (ViewGroup) cardRecyclerView.getParent(), false);
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleBackLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        cardBrandGoodsLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CardHomeActivity.this, CardBrandGoodsActivity.class)
                        .putExtra("brandName", cardBrandAdapter.getData().get(positionInDataSet).getBrand()));
            }
        });
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        getCardBrandInfo();
    }

    private void getCardHomeInfo() {
        new GetCardClassifyTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                CardHomeInfo cardHomeInfo = (CardHomeInfo) o;
                if (!Preconditions.isNullOrEmpty(cardHomeInfo)) {
                    handleCardHomeAdapter(cardHomeInfo);
                }
            }
        }).execute();
    }

    private void getCardBrandInfo() {
        new GetCardBrandTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                cardBrandInfo = (CardBrandInfo) o;
                if (!Preconditions.isNullOrEmpty(cardBrandInfo) && !Preconditions.isNullOrEmpty(cardBrandInfo.get_embedded().getContent())) {
                    handleCardBrandAdapter(cardBrandInfo);
                    getCardHomeInfo();
                } else {
                    SHelper.vis(no_data_empty);
                    emptyTxt.setText("暂无卡包！");
                }
            }
        }).execute();
    }

    private void handleCardBrandGoodsAdapter(String brandName, CardBrandInfo cardBrandInfo) {
        if (cardBrandCategoryAdapter == null) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
            card_brand_recyclerView.setHasFixedSize(true);
            card_brand_recyclerView.setFocusable(false);
            card_brand_recyclerView.setLayoutManager(gridLayoutManager);
            if (!Preconditions.isNullOrEmpty(cardBrandGoods(brandName, cardBrandInfo))) {
                cardBrandCategoryAdapter = new CardBrandCategoryAdapter(cardBrandGoods(brandName, cardBrandInfo).getContent());
                card_brand_recyclerView.setAdapter(cardBrandCategoryAdapter);
                SHelper.vis(card_brand_recyclerView);
                showCardBrandMore(cardBrandGoods(brandName, cardBrandInfo));
                cardBrandCategoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        ARouter.getInstance()
                                .build(RouterIntentConstant.MODULE_SHOPPING_GOODS_DETAIL)
                                .withString("url", cardBrandCategoryAdapter.getData().get(position).get_links().getSelf().getHref())
                                .withInt("goodFrom", 0)
                                .navigation();
                    }
                });
            } else {
                SHelper.gone(card_brand_recyclerView, cardBrandGoodsLayout);
            }
        } else {
            if (!Preconditions.isNullOrEmpty(cardBrandGoods(brandName, cardBrandInfo))) {
                cardBrandCategoryAdapter.setNewData(cardBrandGoods(brandName, cardBrandInfo).getContent());
                showCardBrandMore(cardBrandGoods(brandName, cardBrandInfo));
                SHelper.vis(card_brand_recyclerView);
            } else {
                SHelper.gone(card_brand_recyclerView, cardBrandGoodsLayout);
            }
        }
    }

    /**
     * 是否显示查看更多View
     *
     * @param embeddedBeanXX
     */
    private void showCardBrandMore(CardBrandInfo.EmbeddedBeanXXX.ContentBeanXX.EmbeddedBeanXX embeddedBeanXX) {
        if (!Preconditions.isNullOrEmpty(embeddedBeanXX) && embeddedBeanXX.getContent().size() > 1) {
            SHelper.vis(cardBrandGoodsLayout);
        } else {
            SHelper.gone(cardBrandGoodsLayout);
        }
    }

    private CardBrandInfo.EmbeddedBeanXXX.ContentBeanXX.EmbeddedBeanXX cardBrandGoods(String brandName, CardBrandInfo cardBrandInfo) {
        CardBrandInfo.EmbeddedBeanXXX cardBrandEmbedded = cardBrandInfo.get_embedded();
        if (!Preconditions.isNullOrEmpty(cardBrandEmbedded)) {
            for (CardBrandInfo.EmbeddedBeanXXX.ContentBeanXX cardBrandItem : cardBrandEmbedded.getContent()) {
                if (cardBrandItem.getBrand().equals(brandName)) {
                    return cardBrandItem.get_embedded();
                }
            }
        }
        return null;
    }

    private void handleCardBrandAdapter(CardBrandInfo cardBrandInfo) {
        cardBrandAdapter = new CardBrandAdapter(cardBrandInfo.get_embedded().getContent());
        cardBrandRv.setSlideOnFling(true);
        cardBrandRv.setAdapter(cardBrandAdapter);
        cardBrandRv.addOnItemChangedListener(this);
        cardBrandRv.addScrollStateChangeListener(this);
        cardBrandRv.scrollToPosition(currentBrandScollPosition());
        cardBrandRv.setItemTransitionTimeMillis(150);
        cardBrandRv.setItemTransformer(new ScaleTransformer.Builder().setMinScale(0.7f).build());
        cardBrandAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                positionInDataSet = position;
                cardBrandNameTv.setText(cardBrandAdapter.getData().get(positionInDataSet).getBrand());
                cardBrandRv.scrollToPosition(positionInDataSet);
                handleCardBrandGoodsAdapter(cardBrandAdapter.getData().get(positionInDataSet).getBrand(), cardBrandInfo);
            }
        });
    }

    /**
     * 品牌当前Position
     *
     * @return
     */
    private int currentBrandScollPosition() {
        if (!Preconditions.isNullOrEmpty(cardBrandInfo.get_embedded().getContent())) {
            if (cardBrandInfo.get_embedded().getContent().size() > 2) {
                if ((cardBrandInfo.get_embedded().getContent().size() % 2) == 0) {
                    return (cardBrandInfo.get_embedded().getContent().size()) / 2;
                } else {
                    return 2;
                }
            } else {
                return 0;
            }
        }
        return 0;
    }

    private void handleCardHomeAdapter(CardHomeInfo cardHomeInfo) {
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this);
        cardRecyclerView.setHasFixedSize(true);
        cardRecyclerView.setFocusable(false);
        cardRecyclerView.setLayoutManager(gridLayoutManager);
        cardHomeAdapter = new CardHomeAdapter(cardHomeInfo.get_embedded().getContent());
        cardHomeAdapter.addHeaderView(headView, 0);
        if (cardHomeInfo.get_embedded().getContent().size() > 1) {
            cardHomeAdapter.setFooterView(footView);
        }
        cardHomeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.card_classify_layout) {
                    startActivity(new Intent(CardHomeActivity.this, CardClassifyGoodsActivity.class)
                            .putExtra("titleName", cardHomeAdapter.getData().get(position).getName())
                            .putExtra("showCategoryId", cardHomeAdapter.getData().get(position).getId() + ""));
                }
            }
        });
        cardRecyclerView.setAdapter(cardHomeAdapter);
    }


    @Override
    public void onCurrentItemChanged(@Nullable RecyclerView.ViewHolder viewHolder, int adapterPosition) {
        positionInDataSet = adapterPosition;
        cardBrandNameTv.setText(cardBrandAdapter.getData().get(positionInDataSet).getBrand());
        handleCardBrandGoodsAdapter(cardBrandAdapter.getData().get(positionInDataSet).getBrand(), cardBrandInfo);
    }

    @Override
    public void onScrollStart(@NonNull RecyclerView.ViewHolder currentItemHolder, int adapterPosition) {

    }

    @Override
    public void onScrollEnd(@NonNull RecyclerView.ViewHolder currentItemHolder, int adapterPosition) {

    }

    @Override
    public void onScroll(float scrollPosition, int currentPosition, int newPosition, @Nullable RecyclerView.ViewHolder currentHolder, @Nullable RecyclerView.ViewHolder newCurrent) {

    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

}
